﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace MJTech.AspNetCore.Authentication.WechatMp
{
    public static class WeChatMpAuthenticationExtensions
	{
		
		public static AuthenticationBuilder AddWeChat(this AuthenticationBuilder builder, Action<WeChatMpOptions> options)
		{
			if (options == null)
			{
				throw new ArgumentNullException(nameof(options));
			}
			
			builder.Services.PostConfigure<WeChatMpOptions>(options);
			builder.Services.AddTransient<ISecureDataFormat<AuthenticationProperties>>(
				serviceprovider => 
				{
					IDataProtectionProvider dpProvider = serviceprovider.GetRequiredService<IDataProtectionProvider>();
					return new SecureDataFormat<AuthenticationProperties>(new PropertiesSerializer(), dpProvider.CreateProtector("mjtech"));
				}
			);
			
			return builder.AddOAuth<WeChatMpOptions,WeChatMpAutenticationHandler>("WeChat", "微信公众号", options);

		}
	}
}
